package com.slaffka.services;

import com.slaffka.model.notification.Message;
import com.slaffka.model.notification.Notification;
import com.slaffka.model.user.User;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: v.tsapaev
 * Date: 24.02.12
 * Time: 1:29
 * To change this template use File | Settings | File Templates.
 */
@Service
public class NotificationService {

    @Autowired
    SessionFactory sessionFactory;
    
    @Autowired
    ServiceFactory service;

    @Transactional
    public List getAllClientNotifications(String sessionId) {
        User user = service.getUserSessionService().getUserBySessionId(sessionId);

        List<Object> allPublicNotifications = sessionFactory.getCurrentSession()
                .createQuery("select n " +
                        "from Notification n " +
                        "left join n.targetUsers tu " +
                       // "left join tu.User u" +
                        "where tu is null or tu = :user " +
                        "order by n.createDate")
                .setParameter("user", user)
                .list();

//        if (user == null){
          //  System.out.println("~~~~");
            for (Object object: allPublicNotifications){
                Notification notification = (Notification)object;
                System.out.println("notification = " + notification.getTargetUsers());
            }
            return allPublicNotifications;
//        }

//        List<Object> allNotifications = sessionFactory.getCurrentSession()
//                .createQuery("select n " +
//                        "from Notification n " +
//                        "left join n.targetUsers tu " +
//                        "where tu = :user")
//                .setParameter("user", user).list();
//        allNotifications.addAll(allPublicNotifications);
//        for (Object object: allNotifications){
//            Notification notification = (Notification)object;
//            System.out.println("notification = " + notification.getTargetUsers());
//        }
//        return allNotifications;
    }

    @Transactional
    public Message sendMessage(String message, HttpSession session) {
        Message entityMessage = new Message();
        //notification.setTargetUsers(null);
        entityMessage.setCreateDate(new Date());
        User currentUser = (User)session.getAttribute("user");
        entityMessage.setOwner(currentUser);
        entityMessage.setText(message);

        sessionFactory.getCurrentSession().save(entityMessage);
        return entityMessage;
    }
}
